package com.wu.common.utils;

import com.wu.common.exception.WexinReqException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;

public class WxstoreUtils {
    private static Logger logger = LoggerFactory.getLogger(WxstoreUtils.class);

    public WxstoreUtils() {
    }

    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        logger.debug("*********HTTPREQUEST START********");
        logger.debug("*********requestUrl is " + requestUrl + " END AND requestMethod IS" + requestMethod + " END AND  outputStr" + outputStr + " END ********");
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();

        try {
            TrustManager[] tm = new TrustManager[]{new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init((KeyManager[])null, tm, new SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }

            OutputStream inputStream1;
            if (null != outputStr) {
                inputStream1 = httpUrlConn.getOutputStream();
                inputStream1.write(outputStr.getBytes("UTF-8"));
                inputStream1.close();
            }

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;

            while((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
            if (jsonObject.containsKey("errcode") && jsonObject.getInt("errcode") != 0) {
                logger.debug("********* ERROR********{}", buffer.toString());
                logger.debug("*********HTTPREQUEST END********");
                throw new WexinReqException("httpRequest Method！errcode=" + jsonObject.getString("errcode") + ",errmsg = " + jsonObject.getString("errmsg"));
            }

            logger.debug("********* SUCCESS END********");
        } catch (ConnectException var14) {
            System.out.println("Weixin server connection timed out.");
        } catch (Exception var15) {
            System.out.println("https request error:{}" + var15.getMessage());
        }

        return jsonObject;
    }

    public static JSONObject httpRequest2(String requestUrl, String requestMethod, byte[] outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();

        try {
            TrustManager[] tm = new TrustManager[]{new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init((KeyManager[])null, tm, new SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }

            OutputStream outputStream;
            if (null != outputStr) {
                outputStream = httpUrlConn.getOutputStream();
                outputStream.write(outputStr);
                outputStream.close();
            }

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;

            while((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException var14) {
            System.out.print("Weixin server connection timed out.");
        } catch (Exception var15) {
            System.out.print("https request error:{}" + var15.getMessage());
        }

        return jsonObject;
    }

    public static void saveHttpImage(String requestUrl, String requestMethod, String outputStr, File target) {
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setConnectTimeout(5000);
            InputStream inStream = conn.getInputStream();
            byte[] data = readInputStream(inStream);
            FileOutputStream outStream = new FileOutputStream(target);
            outStream.write(data);
            outStream.close();
        } catch (Exception var9) {
        }

    }

    public static String encode(byte[] bstr) {
        return (new BASE64Encoder()).encode(bstr);
    }

    public static byte[] decode(String str) {
        byte[] bt = null;

        try {
            BASE64Decoder decoder = new BASE64Decoder();
            bt = decoder.decodeBuffer(str);
        } catch (IOException var3) {
            var3.printStackTrace();
        }

        return bt;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        boolean var3 = true;

        int len;
        while((len = inStream.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }

        outstream.close();
        inStream.close();
        return outstream.toByteArray();
    }

    public static JSONObject uploadMediaFile(String requestUrl, File file, String content_type) {
        JSONObject jsonObject = null;
        StringBuffer bufferStr = new StringBuffer();
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        URL submit = null;
        DataOutputStream dos = null;
        BufferedInputStream bufin = null;
        BufferedReader bufferedReader = null;

        try {
            submit = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection)submit.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + file + "\";filename=\"" + file.getName() + ";Content-Type=\"" + content_type + end);
            dos.writeBytes(end);
            bufin = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[8192];
            boolean var14 = false;

            int count;
            while((count = bufin.read(buffer)) != -1) {
                dos.write(buffer, 0, count);
            }

            bufin.close();
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;

            while((str = bufferedReader.readLine()) != null) {
                bufferStr.append(str);
            }

            jsonObject = JSONObject.fromObject(bufferStr.toString());
        } catch (Exception var26) {
            System.err.println("异常错误:" + var26.toString());
            System.err.println("连接地址是:" + requestUrl);
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }

                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (Exception var25) {
            }

        }

        return jsonObject;
    }

    public static JSONObject uploadMediaFileNews(String requestUrl, File file, String content_type) {
        String result = null;
        JSONObject jsonObject = null;
        URL submit = null;
        if (file.exists() && file.isFile()) {
            try {
                submit = new URL(requestUrl);
                HttpURLConnection conn = (HttpURLConnection)submit.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "UTF-8");
                String BOUNDARY = "----------" + System.currentTimeMillis();
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                StringBuilder sb = new StringBuilder();
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
                sb.append("Content-Type:application/octet-stream\r\n\r\n");
                byte[] head = sb.toString().getBytes("utf-8");
                OutputStream out = new DataOutputStream(conn.getOutputStream());
                out.write(head);
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                byte[] bufferOut = new byte[1024];

                int bytes;
                while((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }

                in.close();
                byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
                out.write(foot);
                out.flush();
                out.close();
                StringBuffer buffer = new StringBuffer();
                BufferedReader reader = null;

                try {
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = null;

                    while(true) {
                        if ((line = reader.readLine()) == null) {
                            if (result == null) {
                                result = buffer.toString();
                            }
                            break;
                        }

                        buffer.append(line);
                    }
                } catch (IOException var22) {
                    logger.info("发送POST请求出现异常！" + var22);
                    var22.printStackTrace();
                    throw new IOException("数据读取异常");
                } finally {
                    if (reader != null) {
                        reader.close();
                    }

                }

                jsonObject = JSONObject.fromObject(result);
            } catch (Exception var24) {
                var24.printStackTrace();
            }
        } else {
            logger.info("------------文件不存在------------------------");
        }

        return jsonObject;
    }

    public static void main(String[] args) {
        String url = "https://api.weibo.com/oauth2/access_token?client_id=3016130400&client_secret=70f22fb9106282e6b5fb55a354f6da43&grant_type=authorization_code&code=9c15c07ea807274c7c413e1d9055d92d&redirect_uri=http://open.weibo.com";
        JSONObject httpRequest = httpRequest(url, "POST", (String)null);
        System.err.println(httpRequest);
    }
}